/**
 * Created by moko1988
 * 2016年01月16日16:10:34
 */
define([
    'backbone',
    'models/partener/list',
    'text!templets/partener/list.htm',
    'text!templets/partener/list-modal-add.htm',
    'utils/dataTableUtil',
    'uploadify'
], function(
    BackBone,
    Model,
    Tpl,
    ModalAdd,
    DataTable
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun',
            'click [role=edit]': 'editFun',
            'click [role=save]': 'saveFun',
            'click [role=del]': 'delFun',
            'click [role=rank]': 'rank'
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';
            this.render();
        },
        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this;
            Model.fetchList({
                type: 'post',
                data: {
                    page: this.page,
                    page_size: this.listRows,
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,
                        count = data.length;
                         _this.pageTotal = page.total_page;

                    _.each(data,function(o, i){

                        var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if (i == 0) {

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                        }
                        if (i == (count - 1)) {

                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        }

                        o.rank = rank_up + rank_down;

                        var btn_edit = '<button class="btn" role="edit" data-id="' + o.id+ '" >修改</button>',
                            btn_del = '<button class="btn" role="del" data-id="' + o.id+ '" >删除</button>';
                        o.btns = btn_edit + btn_del;
                    })

                    var tableHead = ['序号', '名称', '链接', '排序', '操作'],
                        tableBody = _.zip(
                            _.pluck(data,'id'),
                            _.pluck(data,'name'),
                            _.pluck(data,'link'),
                            _.pluck(data,'rank'),
                            _.pluck(data,'btns')
                        );
                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                     $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });
                }
            })
        },
         /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.render();
        },

        addFun: function(){
            $(this.el).append(ModalAdd);
            var $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                _this = this;
            $myModal.find('h4').html('添加客户');
            $myModal.off();
            $myModal.modal();
            this.uploadifyIni();
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });
        },
        /*修改*/
        editFun: function(e){
            $(this.el).append(ModalAdd);
            var $target = $(e.currentTarget),
                $myModal = $('#myModal'),
                id = $target.attr('data-id'),
                _this = this;

            $myModal.off();
            $myModal.modal();
            $myModal.find('h4').html('修改客户信息');
            $myModal.find('[role=save]').prop('disabled', true);
            this.uploadifyIni();
            /*弹窗关闭*/
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });
            $('#loading').html(loading);
            $('#data-form').hide();
            Model.fetchInfo({
                type: 'post',
                data: {
                    id: id
                },
                success: function(map) {
                    $myModal.find('input[name=id]').val(id);
                    $myModal.find('input[name=name]').val(map.name);
                    // $myModal.find('input[name=width]').val(map.size_w);
                    // $myModal.find('input[name=height]').val(map.size_h);
                    $myModal.find('input[name=key]').val(map.link);
                    map.picture != '' && _this.imgEcho($myModal.find('input[name=litpic]'), map.picture);

                    $('#loading').html('');
                    $('#data-form').show();
                    $myModal.find('[role=save]').prop('disabled', false);
                }
            })
        },
        /*编辑图片回显*/
        imgEcho: function($target, val) {
            var $wrap = $('#resFile'),
                $info = $wrap.find('.file-info'),
                $val = $wrap.find('.file-val');

            $target.val(val);
            $info.addClass('hide');
            $val.removeClass('hide').find('img').attr('src', 'http://shihai.oss-cn-beijing.aliyuncs.com/' + val);
            $wrap.find('.uploadify').css('z-index', -1);
        },
        /*保存*/
        saveFun: function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=save]'),
                isOK = this.checkForm();
            if (isOK) {
                subBtn.prop('disabled', true);
                Model.save({
                    type:'post',
                    data: $form.serialize(),
                    success: function(map) {
                        subBtn.prop('disabled', false);
                        jAlert('提交成功', function() {
                            $myModal.modal('hide');
                            _this.render();
                        })
                    },
                    error:function(msg){
                        jAlert(msg,function(){
                            subBtn.prop('disabled', false);
                        })
                    }
                })
            }
        },
        /*验证*/
        checkForm: function() {
            var $form = $('[role=form]'),
                $name = $form.find('input[name=name]'),
                $width = $form.find('input[name=width]'),
                $height = $form.find('input[name=height]'),
                $key = $form.find('input[name=key]'),
                errShow = function(e, msg) {
                    var $err = e.siblings('em');
                    $err.html(msg).css("opacity", '1');
                    $err.stop(0, 0).animate({
                        "opacity": 0
                    }, 3500);
                    rest = false;
                },
                rest = true;
            if ($name.val() == '') {
                errShow($name, '请填写合作客户！');
            }

            if ($key.val() == '') {
                errShow($key, '请填写链接！');
            }
            return rest;
        },
        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.attr('data-id'),
                _this = this,
                msg = '<p>确定要删除该客户？</p>';
            jConfirm(msg, function(s) {
                if (s) {
                    Model.delete({
                        data: {
                            id: id
                        },
                        success: function(map) {
                            jAlert('删除成功', function() {
                                _this.render();
                            })
                        }
                    })
                }
            })
        },
        rank: function(e){
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                type:'post',
                data: {
                    id: id,
                    type: type
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                }
            })
        },
        /*初始化uploadify上传按钮*/
        uploadifyIni: function() {

            var $upload = $('#file-upload'),
                $fileCanvas = $('#file-canvas'),
                $info = $fileCanvas.find('.file-info'),
                $loading = $fileCanvas.find('.file-loading'),
                $val = $fileCanvas.find('.file-val'),
                _this = this;

            $loading.html(loading2);
            $upload.uploadify({
                height: 24,
                width: 43,
                removeTimeout: 1,
                buttonText: '上传',
                fileTypeExts: '.*',
                fileSizeLimit: '4MB', //上传文件大小限制
                multi: false, //是否可以上传多个文件
                swf: '/Public/admin/images/uploadify.swf', //上传flash地址（注意路径）
                uploader: adminPath + '/index/uploadfile', //上传数据处理文件Ajax（注意路径）
                /*开始上传之前触发*/
                onUploadStart: function() {

                    $info.addClass('hide');
                    $loading.removeClass('hide');
                    $('#file-upload').css('z-index', -1);
                },
                /*上传完成之后触发*/
                onUploadSuccess: function(file, data, response) {

                    if (response) {
                        data = $.parseJSON(data);
                        if (data.code == 1) {
                            $('input[name=litpic]').val(data.filename);
                            $val.removeClass('hide');
                            $val.find('img').attr('src', 'http://shihai.oss-cn-beijing.aliyuncs.com/' + data.filename);
                            $loading.addClass('hide');
                        } else {
                            jAlert(data.msg, function() {
                                $info.removeClass('hide');
                                $loading.addClass('hide');
                                $('#file-upload').css('z-index', 1);
                            });
                        }
                    }
                }
            })

            /*鼠标经过上传完的图片隐藏展示删除按钮*/
            $val.hover(function() {
                $(this).find('i').show();
            }, function() {
                $(this).find('i').hide();
            });
            /*鼠标经过上传面板隐藏展示上传按钮*/
            $fileCanvas.hover(function() {
                $('#file-upload-button').show();
            }, function() {
                $('#file-upload-button').hide();
            });
            /*点击删除图片按钮*/
            $val.find('i').click(function() {
                _this.resetfileCanvas();
            });
        },
        /*还原上传面板*/
        resetfileCanvas: function() {
            $('input[name=picture_filename]').val('');
            $('.file-val').addClass('hide');
            $('.file-info').removeClass('hide');
            $('#file-upload').css('z-index', 1);
        }
    })
    return view;
})